<template>
    <Toolbar
    class="toolbar"
    :editor="editorRef"
    :defaultConfig="toolbarConfig"
    :mode="mode"
    />
    <Editor
    v-model="value"
    :defaultConfig="editorConfig"
    :mode="mode"
    @onCreated="handleCreated"
    @onChange="handleChange"
    class="overflow-y-auto"
    />
</template>

<script lang="ts" setup>
// declare var require: any
import { onBeforeUnmount, reactive, ref, shallowRef, watch } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import type { IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import formulaModule from '@wangeditor/plugin-formula';
import { Boot } from '@wangeditor/editor';
import { baseURL, getCookie, onNoLogin } from '@/Utils/utils';

if (Boot.plugins.length < 13) {
    Boot.registerModule(formulaModule);
}

const emit = defineEmits(['update:modelValue', 'change', 'receivedList']);

const props = defineProps<{
    modelValue?: string;
}>();

const editorRef = shallowRef();

// onMounted(() => {
//     const doc = new Mergely('#compare', {
//         lhs: (setValue: Function) => {
//             setValue(`111111111112`)
//         },
//         rhs: (setValue: Function) => {
//             setValue(`111111111111`)
//         },
//         license: 'lgpl'
//     });
// })

const value = ref('<p></p>');

const mode = ref('simple');

// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
    excludeKeys: ['group-video', 'insertVideo', 'fullScreen'],
    insertKeys: {
        index: 0,
        keys: [
            'insertFormula', // “插入公式”菜单
            'editFormula' // “编辑公式”菜单
        ],
    },
};

type InsertFnType = (url: string, alt: string, href: string) => void;

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = reactive({ 
    placeholder: '请输入...',
    autoFocus: true,
    MENU_CONF: {
        uploadImage: {
            server: `${baseURL}/file/upload`,
            fieldName: 'file',
            maxFileSize: 10 * 1024 * 1024,
            // 自定义插入图片
            customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
                // res 即服务端的返回结果
                console.log('res: ', res);
                if (!res) return;
                if (res.code == 5) {
                    onNoLogin();
                }
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(res.data.url, res.data.fileName, res.data.url);
            },
            // base64LimitSize: 5 * 1024, // 5kb
            // 上传错误，或者触发 timeout 超时
            onError(file: File, err: any, res: any) {  // TS 语法
                console.log(`${file.name} 上传出错`, err, res)
            },
            headers: {
                userId: getCookie("userId"),
                token: getCookie("token")
            }
        },
    },
    hoverbarKeys: {
        formula: {
            menuKeys: ['editFormula'], // “编辑公式”菜单
        },
    },
});

const handleCreated = (editor: any) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
    // console.log(editorRef.value.getAllMenuKeys())
    // nextTick(() => {
    //     const toolbar = DomEditor.getToolbar(editor)
    //     console.log('toolbar: ', toolbar);

    //     if (toolbar) {
    //         console.log(toolbar.getConfig())
    //     }
    // })
};

const handleChange = () => {
    // console.log(valueHtml.value);
    change();
};

const change = (valueHtml = value.value) => {
    emit('update:modelValue', valueHtml);
    emit('change', valueHtml);
};

defineExpose({
    setHtml (html = '') {
        if (editorRef.value && typeof editorRef.value.setHtml === 'function') {
            editorRef.value.setHtml(html.trim());
        }
    },
    getHtml () {
        if (editorRef.value && typeof editorRef.value.getHtml === 'function') {
            return editorRef.value.getHtml();
        }
        return '';
    },
    destroy: () => {
        const editor = editorRef.value;
        if (editor == null) return;
        editor.destroy();
    }
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

watch(
    () => props.modelValue,
    () => {
        if (value.value != props.modelValue) {
            value.value = props.modelValue || '<p></p>';
        }
        // if (value.value === '<p></p>') {
        //     editorRef.value.undo();
        // }
    }
);
</script>

<style lang="scss" scoped>
.toolbar {
    border-bottom: 1px solid #fff0f0;
}
</style>